home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / threading.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  41KB  |  1,259 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. """Thread module emulating a subset of Java's threading model."""
  5. import sys as _sys
  6.  
  7. try:
  8.     import thread
  9. except ImportError:
  10.     del _sys.modules[__name__]
  11.     raise 
  12.  
  13. import warnings
  14. from collections import deque as _deque
  15. from time import time as _time, sleep as _sleep
  16. from traceback import format_exc as _format_exc
  17. __all__ = [
  18.     'activeCount',
  19.     'active_count',
  20.     'Condition',
  21.     'currentThread',
  22.     'current_thread',
  23.     'enumerate',
  24.     'Event',
  25.     'Lock',
  26.     'RLock',
  27.     'Semaphore',
  28.     'BoundedSemaphore',
  29.     'Thread',
  30.     'Timer',
  31.     'setprofile',
  32.     'settrace',
  33.     'local',
  34.     'stack_size']
  35. _start_new_thread = thread.start_new_thread
  36. _allocate_lock = thread.allocate_lock
  37. _get_ident = thread.get_ident
  38. ThreadError = thread.error
  39. del thread
  40. warnings.filterwarnings('ignore', category = DeprecationWarning, module = 'threading', message = 'sys.exc_clear')
  41. _VERBOSE = False
  42.  
  43. class _Verbose(object):
  44.     
  45.     def __init__(self, verbose = None):
  46.         if verbose is None:
  47.             verbose = _VERBOSE
  48.         self._Verbose__verbose = verbose
  49.  
  50.     
  51.     def _note(self, format, *args):
  52.         if self._Verbose__verbose:
  53.             format = format % args
  54.             ident = _get_ident()
  55.             
  56.             try:
  57.                 name = _active[ident].name
  58.             except KeyError:
  59.                 name = '<OS thread %d>' % ident
  60.  
  61.             format = '%s: %s\n' % (name, format)
  62.             _sys.stderr.write(format)
  63.  
  64.  
  65. _profile_hook = None
  66. _trace_hook = None
  67.  
  68. def setprofile(func):
  69.     '''Set a profile function for all threads started from the threading module.
  70.  
  71.     The func will be passed to sys.setprofile() for each thread, before its
  72.     run() method is called.
  73.  
  74.     '''
  75.     global _profile_hook
  76.     _profile_hook = func
  77.  
  78.  
  79. def settrace(func):
  80.     '''Set a trace function for all threads started from the threading module.
  81.  
  82.     The func will be passed to sys.settrace() for each thread, before its run()
  83.     method is called.
  84.  
  85.     '''
  86.     global _trace_hook
  87.     _trace_hook = func
  88.  
  89. Lock = _allocate_lock
  90.  
  91. def RLock(*args, **kwargs):
  92.     '''Factory function that returns a new reentrant lock.
  93.  
  94.     A reentrant lock must be released by the thread that acquired it. Once a
  95.     thread has acquired a reentrant lock, the same thread may acquire it again
  96.     without blocking; the thread must release it once for each time it has
  97.     acquired it.
  98.  
  99.     '''
  100.     return _RLock(*args, **kwargs)
  101.  
  102.  
  103. class _RLock(_Verbose):
  104.     '''A reentrant lock must be released by the thread that acquired it. Once a
  105.        thread has acquired a reentrant lock, the same thread may acquire it
  106.        again without blocking; the thread must release it once for each time it
  107.        has acquired it.
  108.     '''
  109.     
  110.     def __init__(self, verbose = None):
  111.         _Verbose.__init__(self, verbose)
  112.         self._RLock__block = _allocate_lock()
  113.         self._RLock__owner = None
  114.         self._RLock__count = 0
  115.  
  116.     
  117.     def __repr__(self):
  118.         owner = self._RLock__owner
  119.         
  120.         try:
  121.             owner = _active[owner].name
  122.         except KeyError:
  123.             pass
  124.  
  125.         return '<%s owner=%r count=%d>' % (self.__class__.__name__, owner, self._RLock__count)
  126.  
  127.     
  128.     def acquire(self, blocking = 1):
  129.         '''Acquire a lock, blocking or non-blocking.
  130.  
  131.         When invoked without arguments: if this thread already owns the lock,
  132.         increment the recursion level by one, and return immediately. Otherwise,
  133.         if another thread owns the lock, block until the lock is unlocked. Once
  134.         the lock is unlocked (not owned by any thread), then grab ownership, set
  135.         the recursion level to one, and return. If more than one thread is
  136.         blocked waiting until the lock is unlocked, only one at a time will be
  137.         able to grab ownership of the lock. There is no return value in this
  138.         case.
  139.  
  140.         When invoked with the blocking argument set to true, do the same thing
  141.         as when called without arguments, and return true.
  142.  
  143.         When invoked with the blocking argument set to false, do not block. If a
  144.         call without an argument would block, return false immediately;
  145.         otherwise, do the same thing as when called without arguments, and
  146.         return true.
  147.  
  148.         '''
  149.         me = _get_ident()
  150.         if self._RLock__owner == me:
  151.             self._RLock__count = self._RLock__count + 1
  152.             self._note('%s.acquire(%s): recursive success', self, blocking)
  153.             return 1
  154.         rc = None._RLock__block.acquire(blocking)
  155.         if rc:
  156.             self._RLock__owner = me
  157.             self._RLock__count = 1
  158.             self._note('%s.acquire(%s): initial success', self, blocking)
  159.         else:
  160.             self._note('%s.acquire(%s): failure', self, blocking)
  161.         return rc
  162.  
  163.     __enter__ = acquire
  164.     
  165.     def release(self):
  166.         '''Release a lock, decrementing the recursion level.
  167.  
  168.         If after the decrement it is zero, reset the lock to unlocked (not owned
  169.         by any thread), and if any other threads are blocked waiting for the
  170.         lock to become unlocked, allow exactly one of them to proceed. If after
  171.         the decrement the recursion level is still nonzero, the lock remains
  172.         locked and owned by the calling thread.
  173.  
  174.         Only call this method when the calling thread owns the lock. A
  175.         RuntimeError is raised if this method is called when the lock is
  176.         unlocked.
  177.  
  178.         There is no return value.
  179.  
  180.         '''
  181.         if self._RLock__owner != _get_ident():
  182.             raise RuntimeError('cannot release un-acquired lock')
  183.         self._RLock__count = count = self._RLock__count - 1
  184.         if not count:
  185.             self._RLock__owner = None
  186.             self._RLock__block.release()
  187.             self._note('%s.release(): final release', self)
  188.         else:
  189.             self._note('%s.release(): non-final release', self)
  190.  
  191.     
  192.     def __exit__(self, t, v, tb):
  193.         self.release()
  194.  
  195.     
  196.     def _acquire_restore(self, count_owner):
  197.         (count, owner) = count_owner
  198.         self._RLock__block.acquire()
  199.         self._RLock__count = count
  200.         self._RLock__owner = owner
  201.         self._note('%s._acquire_restore()', self)
  202.  
  203.     
  204.     def _release_save(self):
  205.         self._note('%s._release_save()', self)
  206.         count = self._RLock__count
  207.         self._RLock__count = 0
  208.         owner = self._RLock__owner
  209.         self._RLock__owner = None
  210.         self._RLock__block.release()
  211.         return (count, owner)
  212.  
  213.     
  214.     def _is_owned(self):
  215.         return self._RLock__owner == _get_ident()
  216.  
  217.  
  218.  
  219. def Condition(*args, **kwargs):
  220.     '''Factory function that returns a new condition variable object.
  221.  
  222.     A condition variable allows one or more threads to wait until they are
  223.     notified by another thread.
  224.  
  225.     If the lock argument is given and not None, it must be a Lock or RLock
  226.     object, and it is used as the underlying lock. Otherwise, a new RLock object
  227.     is created and used as the underlying lock.
  228.  
  229.     '''
  230.     return _Condition(*args, **kwargs)
  231.  
  232.  
  233. class _Condition(_Verbose):
  234.     '''Condition variables allow one or more threads to wait until they are
  235.        notified by another thread.
  236.     '''
  237.     
  238.     def __init__(self, lock = None, verbose = None):
  239.         _Verbose.__init__(self, verbose)
  240.         if lock is None:
  241.             lock = RLock()
  242.         self._Condition__lock = lock
  243.         self.acquire = lock.acquire
  244.         self.release = lock.release
  245.         
  246.         try:
  247.             self._release_save = lock._release_save
  248.         except AttributeError:
  249.             pass
  250.  
  251.         
  252.         try:
  253.             self._acquire_restore = lock._acquire_restore
  254.         except AttributeError:
  255.             pass
  256.  
  257.         
  258.         try:
  259.             self._is_owned = lock._is_owned
  260.         except AttributeError:
  261.             pass
  262.  
  263.         self._Condition__waiters = []
  264.  
  265.     
  266.     def __enter__(self):
  267.         return self._Condition__lock.__enter__()
  268.  
  269.     
  270.     def __exit__(self, *args):
  271.         return self._Condition__lock.__exit__(*args)
  272.  
  273.     
  274.     def __repr__(self):
  275.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  276.  
  277.     
  278.     def _release_save(self):
  279.         self._Condition__lock.release()
  280.  
  281.     
  282.     def _acquire_restore(self, x):
  283.         self._Condition__lock.acquire()
  284.  
  285.     
  286.     def _is_owned(self):
  287.         if self._Condition__lock.acquire(0):
  288.             self._Condition__lock.release()
  289.             return False
  290.         return None
  291.  
  292.     
  293.     def wait(self, timeout = None):
  294.         '''Wait until notified or until a timeout occurs.
  295.  
  296.         If the calling thread has not acquired the lock when this method is
  297.         called, a RuntimeError is raised.
  298.  
  299.         This method releases the underlying lock, and then blocks until it is
  300.         awakened by a notify() or notifyAll() call for the same condition
  301.         variable in another thread, or until the optional timeout occurs. Once
  302.         awakened or timed out, it re-acquires the lock and returns.
  303.  
  304.         When the timeout argument is present and not None, it should be a
  305.         floating point number specifying a timeout for the operation in seconds
  306.         (or fractions thereof).
  307.  
  308.         When the underlying lock is an RLock, it is not released using its
  309.         release() method, since this may not actually unlock the lock when it
  310.         was acquired multiple times recursively. Instead, an internal interface
  311.         of the RLock class is used, which really unlocks it even when it has
  312.         been recursively acquired several times. Another internal interface is
  313.         then used to restore the recursion level when the lock is reacquired.
  314.  
  315.         '''
  316.         if not self._is_owned():
  317.             raise RuntimeError('cannot wait on un-acquired lock')
  318.         waiter = _allocate_lock()
  319.         waiter.acquire()
  320.         self._Condition__waiters.append(waiter)
  321.         saved_state = self._release_save()
  322.         
  323.         try:
  324.             if timeout is None:
  325.                 waiter.acquire()
  326.                 self._note('%s.wait(): got it', self)
  327.             else:
  328.                 endtime = _time() + timeout
  329.                 delay = 0.0005
  330.                 while True:
  331.                     gotit = waiter.acquire(0)
  332.                     if gotit:
  333.                         break
  334.                     remaining = endtime - _time()
  335.                     if remaining <= 0:
  336.                         break
  337.                     delay = min(delay * 2, remaining, 0.05)
  338.                     _sleep(delay)
  339.                 if not gotit:
  340.                     self._note('%s.wait(%s): timed out', self, timeout)
  341.                     
  342.                     try:
  343.                         self._Condition__waiters.remove(waiter)
  344.                     except ValueError:
  345.                         pass
  346.                     
  347.  
  348.                 self._note('%s.wait(%s): got it', self, timeout)
  349.         finally:
  350.             self._acquire_restore(saved_state)
  351.  
  352.  
  353.     
  354.     def notify(self, n = 1):
  355.         '''Wake up one or more threads waiting on this condition, if any.
  356.  
  357.         If the calling thread has not acquired the lock when this method is
  358.         called, a RuntimeError is raised.
  359.  
  360.         This method wakes up at most n of the threads waiting for the condition
  361.         variable; it is a no-op if no threads are waiting.
  362.  
  363.         '''
  364.         if not self._is_owned():
  365.             raise RuntimeError('cannot notify on un-acquired lock')
  366.         _Condition__waiters = self._Condition__waiters
  367.         waiters = _Condition__waiters[:n]
  368.         None(None._note, '%s.notify(): notifying %d waiter%s', self, n if not waiters else '')
  369.         for waiter in waiters:
  370.             waiter.release()
  371.             
  372.             try:
  373.                 _Condition__waiters.remove(waiter)
  374.             continue
  375.             except ValueError:
  376.                 continue
  377.             
  378.  
  379.         
  380.  
  381.     
  382.     def notifyAll(self):
  383.         '''Wake up all threads waiting on this condition.
  384.  
  385.         If the calling thread has not acquired the lock when this method
  386.         is called, a RuntimeError is raised.
  387.  
  388.         '''
  389.         self.notify(len(self._Condition__waiters))
  390.  
  391.     notify_all = notifyAll
  392.  
  393.  
  394. def Semaphore(*args, **kwargs):
  395.     '''A factory function that returns a new semaphore.
  396.  
  397.     Semaphores manage a counter representing the number of release() calls minus
  398.     the number of acquire() calls, plus an initial value. The acquire() method
  399.     blocks if necessary until it can return without making the counter
  400.     negative. If not given, value defaults to 1.
  401.  
  402.     '''
  403.     return _Semaphore(*args, **kwargs)
  404.  
  405.  
  406. class _Semaphore(_Verbose):
  407.     '''Semaphores manage a counter representing the number of release() calls
  408.        minus the number of acquire() calls, plus an initial value. The acquire()
  409.        method blocks if necessary until it can return without making the counter
  410.        negative. If not given, value defaults to 1.
  411.  
  412.     '''
  413.     
  414.     def __init__(self, value = 1, verbose = None):
  415.         if value < 0:
  416.             raise ValueError('semaphore initial value must be >= 0')
  417.         _Verbose.__init__(self, verbose)
  418.         self._Semaphore__cond = Condition(Lock())
  419.         self._Semaphore__value = value
  420.  
  421.     
  422.     def acquire(self, blocking = 1):
  423.         '''Acquire a semaphore, decrementing the internal counter by one.
  424.  
  425.         When invoked without arguments: if the internal counter is larger than
  426.         zero on entry, decrement it by one and return immediately. If it is zero
  427.         on entry, block, waiting until some other thread has called release() to
  428.         make it larger than zero. This is done with proper interlocking so that
  429.         if multiple acquire() calls are blocked, release() will wake exactly one
  430.         of them up. The implementation may pick one at random, so the order in
  431.         which blocked threads are awakened should not be relied on. There is no
  432.         return value in this case.
  433.  
  434.         When invoked with blocking set to true, do the same thing as when called
  435.         without arguments, and return true.
  436.  
  437.         When invoked with blocking set to false, do not block. If a call without
  438.         an argument would block, return false immediately; otherwise, do the
  439.         same thing as when called without arguments, and return true.
  440.  
  441.         '''
  442.         rc = False
  443.         with self._Semaphore__cond:
  444.             while self._Semaphore__value == 0:
  445.                 if not blocking:
  446.                     break
  447.                 self._note('%s.acquire(%s): blocked waiting, value=%s', self, blocking, self._Semaphore__value)
  448.                 self._Semaphore__cond.wait()
  449.             self._Semaphore__value = self._Semaphore__value - 1
  450.             self._note('%s.acquire: success, value=%s', self, self._Semaphore__value)
  451.             rc = True
  452.         return rc
  453.  
  454.     __enter__ = acquire
  455.     
  456.     def release(self):
  457.         '''Release a semaphore, incrementing the internal counter by one.
  458.  
  459.         When the counter is zero on entry and another thread is waiting for it
  460.         to become larger than zero again, wake up that thread.
  461.  
  462.         '''
  463.         with self._Semaphore__cond:
  464.             self._Semaphore__value = self._Semaphore__value + 1
  465.             self._note('%s.release: success, value=%s', self, self._Semaphore__value)
  466.             self._Semaphore__cond.notify()
  467.  
  468.     
  469.     def __exit__(self, t, v, tb):
  470.         self.release()
  471.  
  472.  
  473.  
  474. def BoundedSemaphore(*args, **kwargs):
  475.     """A factory function that returns a new bounded semaphore.
  476.  
  477.     A bounded semaphore checks to make sure its current value doesn't exceed its
  478.     initial value. If it does, ValueError is raised. In most situations
  479.     semaphores are used to guard resources with limited capacity.
  480.  
  481.     If the semaphore is released too many times it's a sign of a bug. If not
  482.     given, value defaults to 1.
  483.  
  484.     Like regular semaphores, bounded semaphores manage a counter representing
  485.     the number of release() calls minus the number of acquire() calls, plus an
  486.     initial value. The acquire() method blocks if necessary until it can return
  487.     without making the counter negative. If not given, value defaults to 1.
  488.  
  489.     """
  490.     return _BoundedSemaphore(*args, **kwargs)
  491.  
  492.  
  493. class _BoundedSemaphore(_Semaphore):
  494.     """A bounded semaphore checks to make sure its current value doesn't exceed
  495.        its initial value. If it does, ValueError is raised. In most situations
  496.        semaphores are used to guard resources with limited capacity.
  497.     """
  498.     
  499.     def __init__(self, value = 1, verbose = None):
  500.         _Semaphore.__init__(self, value, verbose)
  501.         self._initial_value = value
  502.  
  503.     
  504.     def release(self):
  505.         '''Release a semaphore, incrementing the internal counter by one.
  506.  
  507.         When the counter is zero on entry and another thread is waiting for it
  508.         to become larger than zero again, wake up that thread.
  509.  
  510.         If the number of releases exceeds the number of acquires,
  511.         raise a ValueError.
  512.  
  513.         '''
  514.         with self._Semaphore__cond:
  515.             if self._Semaphore__value >= self._initial_value:
  516.                 raise ValueError('Semaphore released too many times')
  517.             self._Semaphore__value += 1
  518.             self._Semaphore__cond.notify()
  519.  
  520.  
  521.  
  522. def Event(*args, **kwargs):
  523.     '''A factory function that returns a new event.
  524.  
  525.     Events manage a flag that can be set to true with the set() method and reset
  526.     to false with the clear() method. The wait() method blocks until the flag is
  527.     true.
  528.  
  529.     '''
  530.     return _Event(*args, **kwargs)
  531.  
  532.  
  533. class _Event(_Verbose):
  534.     '''A factory function that returns a new event object. An event manages a
  535.        flag that can be set to true with the set() method and reset to false
  536.        with the clear() method. The wait() method blocks until the flag is true.
  537.  
  538.     '''
  539.     
  540.     def __init__(self, verbose = None):
  541.         _Verbose.__init__(self, verbose)
  542.         self._Event__cond = Condition(Lock())
  543.         self._Event__flag = False
  544.  
  545.     
  546.     def _reset_internal_locks(self):
  547.         self._Event__cond.__init__()
  548.  
  549.     
  550.     def isSet(self):
  551.         '''Return true if and only if the internal flag is true.'''
  552.         return self._Event__flag
  553.  
  554.     is_set = isSet
  555.     
  556.     def set(self):
  557.         '''Set the internal flag to true.
  558.  
  559.         All threads waiting for the flag to become true are awakened. Threads
  560.         that call wait() once the flag is true will not block at all.
  561.  
  562.         '''
  563.         self._Event__cond.acquire()
  564.         
  565.         try:
  566.             self._Event__flag = True
  567.             self._Event__cond.notify_all()
  568.         finally:
  569.             self._Event__cond.release()
  570.  
  571.  
  572.     
  573.     def clear(self):
  574.         '''Reset the internal flag to false.
  575.  
  576.         Subsequently, threads calling wait() will block until set() is called to
  577.         set the internal flag to true again.
  578.  
  579.         '''
  580.         self._Event__cond.acquire()
  581.         
  582.         try:
  583.             self._Event__flag = False
  584.         finally:
  585.             self._Event__cond.release()
  586.  
  587.  
  588.     
  589.     def wait(self, timeout = None):
  590.         '''Block until the internal flag is true.
  591.  
  592.         If the internal flag is true on entry, return immediately. Otherwise,
  593.         block until another thread calls set() to set the flag to true, or until
  594.         the optional timeout occurs.
  595.  
  596.         When the timeout argument is present and not None, it should be a
  597.         floating point number specifying a timeout for the operation in seconds
  598.         (or fractions thereof).
  599.  
  600.         This method returns the internal flag on exit, so it will always return
  601.         True except if a timeout is given and the operation times out.
  602.  
  603.         '''
  604.         self._Event__cond.acquire()
  605.         
  606.         try:
  607.             if not self._Event__flag:
  608.                 self._Event__cond.wait(timeout)
  609.             return self._Event__flag
  610.         finally:
  611.             self._Event__cond.release()
  612.  
  613.  
  614.  
  615. _counter = 0
  616.  
  617. def _newname(template = 'Thread-%d'):
  618.     global _counter
  619.     _counter = _counter + 1
  620.     return template % _counter
  621.  
  622. _active_limbo_lock = _allocate_lock()
  623. _active = { }
  624. _limbo = { }
  625.  
  626. class Thread(_Verbose):
  627.     '''A class that represents a thread of control.
  628.  
  629.     This class can be safely subclassed in a limited fashion.
  630.  
  631.     '''
  632.     __initialized = False
  633.     __exc_info = _sys.exc_info
  634.     __exc_clear = _sys.exc_clear
  635.     
  636.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, verbose = None):
  637.         '''This constructor should always be called with keyword arguments. Arguments are:
  638.  
  639.         *group* should be None; reserved for future extension when a ThreadGroup
  640.         class is implemented.
  641.  
  642.         *target* is the callable object to be invoked by the run()
  643.         method. Defaults to None, meaning nothing is called.
  644.  
  645.         *name* is the thread name. By default, a unique name is constructed of
  646.         the form "Thread-N" where N is a small decimal number.
  647.  
  648.         *args* is the argument tuple for the target invocation. Defaults to ().
  649.  
  650.         *kwargs* is a dictionary of keyword arguments for the target
  651.         invocation. Defaults to {}.
  652.  
  653.         If a subclass overrides the constructor, it must make sure to invoke
  654.         the base class constructor (Thread.__init__()) before doing anything
  655.         else to the thread.
  656.  
  657. '''
  658.         if not group is None:
  659.             raise AssertionError('group argument must be None for now')
  660.         None.__init__(self, verbose)
  661.         if kwargs is None:
  662.             kwargs = { }
  663.         self._Thread__target = target
  664.         if not name:
  665.             pass
  666.         self._Thread__name = str(_newname())
  667.         self._Thread__args = args
  668.         self._Thread__kwargs = kwargs
  669.         self._Thread__daemonic = self._set_daemon()
  670.         self._Thread__ident = None
  671.         self._Thread__started = Event()
  672.         self._Thread__stopped = False
  673.         self._Thread__block = Condition(Lock())
  674.         self._Thread__initialized = True
  675.         self._Thread__stderr = _sys.stderr
  676.  
  677.     
  678.     def _reset_internal_locks(self):
  679.         if hasattr(self, '_Thread__block'):
  680.             self._Thread__block.__init__()
  681.         self._Thread__started._reset_internal_locks()
  682.  
  683.     
  684.     def _block(self):
  685.         return self._Thread__block
  686.  
  687.     _block = property(_block)
  688.     
  689.     def _set_daemon(self):
  690.         return current_thread().daemon
  691.  
  692.     
  693.     def __repr__(self):
  694.         if not self._Thread__initialized:
  695.             raise AssertionError('Thread.__init__() was not called')
  696.         status = None
  697.         if self._Thread__started.is_set():
  698.             status = 'started'
  699.         if self._Thread__stopped:
  700.             status = 'stopped'
  701.         if self._Thread__daemonic:
  702.             status += ' daemon'
  703.         if self._Thread__ident is not None:
  704.             status += ' %s' % self._Thread__ident
  705.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  706.  
  707.     
  708.     def start(self):
  709.         """Start the thread's activity.
  710.  
  711.         It must be called at most once per thread object. It arranges for the
  712.         object's run() method to be invoked in a separate thread of control.
  713.  
  714.         This method will raise a RuntimeError if called more than once on the
  715.         same thread object.
  716.  
  717.         """
  718.         if not self._Thread__initialized:
  719.             raise RuntimeError('thread.__init__() not called')
  720.         if self._Thread__started.is_set():
  721.             raise RuntimeError('threads can only be started once')
  722.         self._note('%s.start(): starting thread', self)
  723.         with _active_limbo_lock:
  724.             _limbo[self] = self
  725.         
  726.         try:
  727.             _start_new_thread(self._Thread__bootstrap, ())
  728.         except Exception:
  729.             with _active_limbo_lock:
  730.                 del _limbo[self]
  731.         else:
  732.             raise 
  733.  
  734.         self._Thread__started.wait()
  735.  
  736.     
  737.     def run(self):
  738.         """Method representing the thread's activity.
  739.  
  740.         You may override this method in a subclass. The standard run() method
  741.         invokes the callable object passed to the object's constructor as the
  742.         target argument, if any, with sequential and keyword arguments taken
  743.         from the args and kwargs arguments, respectively.
  744.  
  745.         """
  746.         
  747.         try:
  748.             if self._Thread__target:
  749.                 self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
  750.         finally:
  751.             del self._Thread__target
  752.             del self._Thread__args
  753.             del self._Thread__kwargs
  754.  
  755.  
  756.     
  757.     def __bootstrap(self):
  758.         
  759.         try:
  760.             self._Thread__bootstrap_inner()
  761.         except:
  762.             if self._Thread__daemonic and _sys is None:
  763.                 return None
  764.  
  765.  
  766.     
  767.     def _set_ident(self):
  768.         self._Thread__ident = _get_ident()
  769.  
  770.     
  771.     def __bootstrap_inner(self):
  772.         
  773.         try:
  774.             self._set_ident()
  775.             self._Thread__started.set()
  776.             with _active_limbo_lock:
  777.                 _active[self._Thread__ident] = self
  778.                 del _limbo[self]
  779.             self._note('%s.__bootstrap(): thread started', self)
  780.             if _trace_hook:
  781.                 self._note('%s.__bootstrap(): registering trace hook', self)
  782.                 _sys.settrace(_trace_hook)
  783.             if _profile_hook:
  784.                 self._note('%s.__bootstrap(): registering profile hook', self)
  785.                 _sys.setprofile(_profile_hook)
  786.             
  787.             try:
  788.                 self.run()
  789.             except SystemExit:
  790.                 self._note('%s.__bootstrap(): raised SystemExit', self)
  791.             except:
  792.                 self._note('%s.__bootstrap(): unhandled exception', self)
  793.                 if _sys:
  794.                     _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.name, _format_exc()))
  795.                 else:
  796.                     (exc_type, exc_value, exc_tb) = self._Thread__exc_info()
  797.                     
  798.                     try:
  799.                         print >>self._Thread__stderr, 'Exception in thread ' + self.name + ' (most likely raised during interpreter shutdown):'
  800.                         print >>self._Thread__stderr, 'Traceback (most recent call last):'
  801.                         while exc_tb:
  802.                             print >>self._Thread__stderr, '  File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)
  803.                             exc_tb = exc_tb.tb_next
  804.                         print >>self._Thread__stderr, '%s: %s' % (exc_type, exc_value)
  805.                     finally:
  806.                         del exc_type
  807.                         del exc_value
  808.                         del exc_tb
  809.  
  810.             else:
  811.                 self._note('%s.__bootstrap(): normal return', self)
  812.             finally:
  813.                 self._Thread__exc_clear()
  814.  
  815.         finally:
  816.             with _active_limbo_lock:
  817.                 self._Thread__stop()
  818.                 
  819.                 try:
  820.                     del _active[_get_ident()]
  821.                 except:
  822.                     pass
  823.  
  824.  
  825.  
  826.     
  827.     def __stop(self):
  828.         if not hasattr(self, '_Thread__block'):
  829.             return None
  830.         None._Thread__block.acquire()
  831.         self._Thread__stopped = True
  832.         self._Thread__block.notify_all()
  833.         self._Thread__block.release()
  834.  
  835.     
  836.     def __delete(self):
  837.         '''Remove current thread from the dict of currently running threads.'''
  838.         
  839.         try:
  840.             with _active_limbo_lock:
  841.                 del _active[_get_ident()]
  842.         except KeyError:
  843.             if 'dummy_threading' not in _sys.modules:
  844.                 raise 
  845.  
  846.  
  847.     
  848.     def join(self, timeout = None):
  849.         '''Wait until the thread terminates.
  850.  
  851.         This blocks the calling thread until the thread whose join() method is
  852.         called terminates -- either normally or through an unhandled exception
  853.         or until the optional timeout occurs.
  854.  
  855.         When the timeout argument is present and not None, it should be a
  856.         floating point number specifying a timeout for the operation in seconds
  857.         (or fractions thereof). As join() always returns None, you must call
  858.         isAlive() after join() to decide whether a timeout happened -- if the
  859.         thread is still alive, the join() call timed out.
  860.  
  861.         When the timeout argument is not present or None, the operation will
  862.         block until the thread terminates.
  863.  
  864.         A thread can be join()ed many times.
  865.  
  866.         join() raises a RuntimeError if an attempt is made to join the current
  867.         thread as that would cause a deadlock. It is also an error to join() a
  868.         thread before it has been started and attempts to do so raises the same
  869.         exception.
  870.  
  871.         '''
  872.         if not self._Thread__initialized:
  873.             raise RuntimeError('Thread.__init__() not called')
  874.         if not self._Thread__started.is_set():
  875.             raise RuntimeError('cannot join thread before it is started')
  876.         if self is current_thread():
  877.             raise RuntimeError('cannot join current thread')
  878.         if not self._Thread__stopped:
  879.             self._note('%s.join(): waiting until thread stops', self)
  880.         self._Thread__block.acquire()
  881.         
  882.         try:
  883.             if timeout is None:
  884.                 while not self._Thread__stopped:
  885.                     self._Thread__block.wait()
  886.                 self._note('%s.join(): thread stopped', self)
  887.             else:
  888.                 deadline = _time() + timeout
  889.                 while not self._Thread__stopped:
  890.                     delay = deadline - _time()
  891.                     if delay <= 0:
  892.                         self._note('%s.join(): timed out', self)
  893.                         break
  894.                     self._Thread__block.wait(delay)
  895.                 self._note('%s.join(): thread stopped', self)
  896.         finally:
  897.             self._Thread__block.release()
  898.  
  899.  
  900.     
  901.     def name(self):
  902.         '''A string used for identification purposes only.
  903.  
  904.         It has no semantics. Multiple threads may be given the same name. The
  905.         initial name is set by the constructor.
  906.  
  907.         '''
  908.         if not self._Thread__initialized:
  909.             raise AssertionError('Thread.__init__() not called')
  910.         return None._Thread__name
  911.  
  912.     name = property(name)
  913.     
  914.     def name(self, name):
  915.         if not self._Thread__initialized:
  916.             raise AssertionError('Thread.__init__() not called')
  917.         self._Thread__name = None(name)
  918.  
  919.     name = name.setter(name)
  920.     
  921.     def ident(self):
  922.         '''Thread identifier of this thread or None if it has not been started.
  923.  
  924.         This is a nonzero integer. See the thread.get_ident() function. Thread
  925.         identifiers may be recycled when a thread exits and another thread is
  926.         created. The identifier is available even after the thread has exited.
  927.  
  928.         '''
  929.         if not self._Thread__initialized:
  930.             raise AssertionError('Thread.__init__() not called')
  931.         return None._Thread__ident
  932.  
  933.     ident = property(ident)
  934.     
  935.     def isAlive(self):
  936.         '''Return whether the thread is alive.
  937.  
  938.         This method returns True just before the run() method starts until just
  939.         after the run() method terminates. The module function enumerate()
  940.         returns a list of all alive threads.
  941.  
  942.         '''
  943.         return None if not self._Thread__initialized else not (self._Thread__stopped)
  944.  
  945.     is_alive = isAlive
  946.     
  947.     def daemon(self):
  948.         '''A boolean value indicating whether this thread is a daemon thread (True) or not (False).
  949.  
  950.         This must be set before start() is called, otherwise RuntimeError is
  951.         raised. Its initial value is inherited from the creating thread; the
  952.         main thread is not a daemon thread and therefore all threads created in
  953.         the main thread default to daemon = False.
  954.  
  955.         The entire Python program exits when no alive non-daemon threads are
  956.         left.
  957.  
  958.         '''
  959.         if not self._Thread__initialized:
  960.             raise AssertionError('Thread.__init__() not called')
  961.         return None._Thread__daemonic
  962.  
  963.     daemon = property(daemon)
  964.     
  965.     def daemon(self, daemonic):
  966.         if not self._Thread__initialized:
  967.             raise RuntimeError('Thread.__init__() not called')
  968.         if self._Thread__started.is_set():
  969.             raise RuntimeError('cannot set daemon status of active thread')
  970.         self._Thread__daemonic = daemonic
  971.  
  972.     daemon = daemon.setter(daemon)
  973.     
  974.     def isDaemon(self):
  975.         return self.daemon
  976.  
  977.     
  978.     def setDaemon(self, daemonic):
  979.         self.daemon = daemonic
  980.  
  981.     
  982.     def getName(self):
  983.         return self.name
  984.  
  985.     
  986.     def setName(self, name):
  987.         self.name = name
  988.  
  989.  
  990.  
  991. def Timer(*args, **kwargs):
  992.     """Factory function to create a Timer object.
  993.  
  994.     Timers call a function after a specified number of seconds:
  995.  
  996.         t = Timer(30.0, f, args=[], kwargs={})
  997.         t.start()
  998.         t.cancel()     # stop the timer's action if it's still waiting
  999.  
  1000.     """
  1001.     return _Timer(*args, **kwargs)
  1002.  
  1003.  
  1004. class _Timer(Thread):
  1005.     """Call a function after a specified number of seconds:
  1006.  
  1007.             t = Timer(30.0, f, args=[], kwargs={})
  1008.             t.start()
  1009.             t.cancel()     # stop the timer's action if it's still waiting
  1010.  
  1011.     """
  1012.     
  1013.     def __init__(self, interval, function, args = [], kwargs = { }):
  1014.         Thread.__init__(self)
  1015.         self.interval = interval
  1016.         self.function = function
  1017.         self.args = args
  1018.         self.kwargs = kwargs
  1019.         self.finished = Event()
  1020.  
  1021.     
  1022.     def cancel(self):
  1023.         """Stop the timer if it hasn't finished yet"""
  1024.         self.finished.set()
  1025.  
  1026.     
  1027.     def run(self):
  1028.         self.finished.wait(self.interval)
  1029.         if not self.finished.is_set():
  1030.             self.function(*self.args, **self.kwargs)
  1031.         self.finished.set()
  1032.  
  1033.  
  1034.  
  1035. class _MainThread(Thread):
  1036.     
  1037.     def __init__(self):
  1038.         Thread.__init__(self, name = 'MainThread')
  1039.         self._Thread__started.set()
  1040.         self._set_ident()
  1041.         with _active_limbo_lock:
  1042.             _active[_get_ident()] = self
  1043.  
  1044.     
  1045.     def _set_daemon(self):
  1046.         return False
  1047.  
  1048.     
  1049.     def _exitfunc(self):
  1050.         self._Thread__stop()
  1051.         t = _pickSomeNonDaemonThread()
  1052.         if t:
  1053.             self._note('%s: waiting for other threads', self)
  1054.         while t:
  1055.             t.join()
  1056.             t = _pickSomeNonDaemonThread()
  1057.         self._note('%s: exiting', self)
  1058.         self._Thread__delete()
  1059.  
  1060.  
  1061.  
  1062. def _pickSomeNonDaemonThread():
  1063.     for t in enumerate():
  1064.         if not (t.daemon) and t.is_alive():
  1065.             return t
  1066.     
  1067.  
  1068.  
  1069. class _DummyThread(Thread):
  1070.     
  1071.     def __init__(self):
  1072.         Thread.__init__(self, name = _newname('Dummy-%d'))
  1073.         del self._Thread__block
  1074.         self._Thread__started.set()
  1075.         self._set_ident()
  1076.         with _active_limbo_lock:
  1077.             _active[_get_ident()] = self
  1078.  
  1079.     
  1080.     def _set_daemon(self):
  1081.         return True
  1082.  
  1083.     
  1084.     def join(self, timeout = None):
  1085.         if not False:
  1086.             raise AssertionError('cannot join a dummy thread')
  1087.  
  1088.  
  1089.  
  1090. def currentThread():
  1091.     """Return the current Thread object, corresponding to the caller's thread of control.
  1092.  
  1093.     If the caller's thread of control was not created through the threading
  1094.     module, a dummy thread object with limited functionality is returned.
  1095.  
  1096.     """
  1097.     
  1098.     try:
  1099.         return _active[_get_ident()]
  1100.     except KeyError:
  1101.         return _DummyThread()
  1102.  
  1103.  
  1104. current_thread = currentThread
  1105.  
  1106. def activeCount():
  1107.     '''Return the number of Thread objects currently alive.
  1108.  
  1109.     The returned count is equal to the length of the list returned by
  1110.     enumerate().
  1111.  
  1112.     '''
  1113.     with _active_limbo_lock:
  1114.         return len(_active) + len(_limbo)
  1115.  
  1116. active_count = activeCount
  1117.  
  1118. def _enumerate():
  1119.     return _active.values() + _limbo.values()
  1120.  
  1121.  
  1122. def enumerate():
  1123.     '''Return a list of all Thread objects currently alive.
  1124.  
  1125.     The list includes daemonic threads, dummy thread objects created by
  1126.     current_thread(), and the main thread. It excludes terminated threads and
  1127.     threads that have not yet been started.
  1128.  
  1129.     '''
  1130.     with _active_limbo_lock:
  1131.         return _active.values() + _limbo.values()
  1132.  
  1133. from thread import stack_size
  1134. _shutdown = _MainThread()._exitfunc
  1135.  
  1136. try:
  1137.     from thread import _local as local
  1138. except ImportError:
  1139.     from _threading_local import local
  1140.  
  1141.  
  1142. def _after_fork():
  1143.     global _active_limbo_lock
  1144.     _active_limbo_lock = _allocate_lock()
  1145.     new_active = { }
  1146.     current = current_thread()
  1147.     with _active_limbo_lock:
  1148.         for thread in _enumerate():
  1149.             if hasattr(thread, '_reset_internal_locks'):
  1150.                 thread._reset_internal_locks()
  1151.             if thread is current:
  1152.                 ident = _get_ident()
  1153.                 thread._Thread__ident = ident
  1154.                 new_active[ident] = thread
  1155.                 continue
  1156.             thread._Thread__stop()
  1157.         
  1158.         _limbo.clear()
  1159.         _active.clear()
  1160.         _active.update(new_active)
  1161.         if not len(_active) == 1:
  1162.             raise AssertionError
  1163.  
  1164.  
  1165. def _test():
  1166.     
  1167.     class BoundedQueue(_Verbose):
  1168.         
  1169.         def __init__(self, limit):
  1170.             _Verbose.__init__(self)
  1171.             self.mon = RLock()
  1172.             self.rc = Condition(self.mon)
  1173.             self.wc = Condition(self.mon)
  1174.             self.limit = limit
  1175.             self.queue = _deque()
  1176.  
  1177.         
  1178.         def put(self, item):
  1179.             self.mon.acquire()
  1180.             while len(self.queue) >= self.limit:
  1181.                 self._note('put(%s): queue full', item)
  1182.                 self.wc.wait()
  1183.             self.queue.append(item)
  1184.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  1185.             self.rc.notify()
  1186.             self.mon.release()
  1187.  
  1188.         
  1189.         def get(self):
  1190.             self.mon.acquire()
  1191.             while not self.queue:
  1192.                 self._note('get(): queue empty')
  1193.                 self.rc.wait()
  1194.             item = self.queue.popleft()
  1195.             self._note('get(): got %s, %d left', item, len(self.queue))
  1196.             self.wc.notify()
  1197.             self.mon.release()
  1198.             return item
  1199.  
  1200.  
  1201.     
  1202.     class ProducerThread(Thread):
  1203.         
  1204.         def __init__(self, queue, quota):
  1205.             Thread.__init__(self, name = 'Producer')
  1206.             self.queue = queue
  1207.             self.quota = quota
  1208.  
  1209.         
  1210.         def run(self):
  1211.             random = random
  1212.             import random
  1213.             counter = 0
  1214.             while counter < self.quota:
  1215.                 counter = counter + 1
  1216.                 self.queue.put('%s.%d' % (self.name, counter))
  1217.                 _sleep(random() * 1e-05)
  1218.  
  1219.  
  1220.     
  1221.     class ConsumerThread(Thread):
  1222.         
  1223.         def __init__(self, queue, count):
  1224.             Thread.__init__(self, name = 'Consumer')
  1225.             self.queue = queue
  1226.             self.count = count
  1227.  
  1228.         
  1229.         def run(self):
  1230.             while self.count > 0:
  1231.                 item = self.queue.get()
  1232.                 print item
  1233.                 self.count = self.count - 1
  1234.  
  1235.  
  1236.     NP = 3
  1237.     QL = 4
  1238.     NI = 5
  1239.     Q = BoundedQueue(QL)
  1240.     P = []
  1241.     for i in range(NP):
  1242.         t = ProducerThread(Q, NI)
  1243.         t.name = 'Producer-%d' % (i + 1)
  1244.         P.append(t)
  1245.     
  1246.     C = ConsumerThread(Q, NI * NP)
  1247.     for t in P:
  1248.         t.start()
  1249.         _sleep(1e-06)
  1250.     
  1251.     C.start()
  1252.     for t in P:
  1253.         t.join()
  1254.     
  1255.     C.join()
  1256.  
  1257. if __name__ == '__main__':
  1258.     _test()
  1259.